<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'; // 引入ElMessage
//引入获取验证码接口
import { reqCode, reqAuthentication } from '../../api/code/index'
import { reqMenuPermissions } from '../../api/menu';
// import { reqLogin } from '../../api/login';
import {useRouter} from 'vue-router'
import {useUserStore} from '../../store/modules/user'
const change = ref(true)
//定义切换登录和注册
const handleChange = () => {
    change.value = !change.value
}

//定义登录规则
const ruleForm = reactive({
    userName: '',
    passWord: '',
    validCode: ''
})

// 手机号格式校验函数
const validateUserName = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请输入账号'))
    } else {
        const phoneRegex = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/; // 简单的手机号正则表达式，可以根据需要调整
        phoneRegex.test(value) ? callback() : callback(new Error('手机号格式不正确'));
    }

}

const validatePassWord = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请输入密码'))
    } else {
        const userNameRegex = /^[a-zA-Z0-9_-]{4,16}$/; // 根据实际需求调整正则表达式
        userNameRegex.test(value) ? callback() : callback(new Error('密码格式不正确'));
    }


}

// // 验证码格式校验函数
// const validateValidCode = (rule, value, callback) => {
//     if (value === '') {
//         callback(new Error('请输入验证码'))
//     } else {
//         const validCodeRegex = /^\d{4}$/; // 简单的验证码正则表达式，要求是4位数字
//         return validCodeRegex.test(validCode);
//     }


    const rules = reactive({
        userName: [
            {
                validator: validateUserName,
                trigger: 'blur'
            }
        ],
        passWord: [
            {
                validator: validatePassWord,
                trigger: 'blur'
            }
        ],
        // validCode: [
        //     {
        //         validator: validateValidCode,
        //         trigger: 'blur'
        //     }
        // ]


    })

    //验证码发送短信
    const countDown = reactive({
        validText: '获取验证码',
        time: 60
    })
    const canClick = ref(true)
    const countDownChange = () => {

        if (!canClick.value) return; // 如果不允许点击则直接返回
        canClick.value = false; // 设置为不允许点击
        countDown.time = 60; // 重置时间
        countDown.validText = `剩余${countDown.time}s`; // 更新显示文本
        //倒计时
        const interval = setInterval(() => {
            if (countDown.time <= 0) {
                clearInterval(interval)
                countDown.validText = '获取验证码'
                countDown.time = 60
                canClick.value = true; // 设置允许点击
            } else {
                countDown.time--
                countDown.validText = `剩余${countDown.time}s`

            }

        }, 1000)

        reqCode({ tel: ruleForm.userName }).then(({ data }) => {
            if (data.code === 10000) {
                ElMessage.success('发送成功')
            }

        })
    }

    //菜单权限数据
    const menuPermissions=async()=>{
        const res=reqMenuPermissions()
        console.log(res);
        
    }

    //注册账号
    const router=useRouter()
    const loginFormRef = ref()
    const userStore=useUserStore()
    const sunmitForm= async (formEl) => {
        if (!formEl) return
        //手动触发校验
        await formEl.validate((valid, fields) => {
            if (valid) {
                //注册页面
                if (!change.value) {
                    reqAuthentication(ruleForm).then(({ data }) => {
                        if (data.code === 10000) {
                            change.value=true
                        }

                    })
                }else{
                    //登录
                    userStore.userLogin(ruleForm)
                    menuPermissions()
                    router.push('/')
                    
                }

            } else {
                console.log('error submit!', fields)
            }
        })


    }

</script>

<template>
    <el-row class='login-container'>
        <el-card style="max-width: 480px;">
            <template #header>
                <div class='card-header'>
                    <img src="../../../public/login-head.png" alt="">
                </div>
            </template>
            <div class="jump-link">
                <el-link @click="handleChange" type="primary" :underline="false">{{ !change ? '返回登录' : '注册账号'
                    }}</el-link>
            </div>
            <el-form ref="loginFormRef" :model="ruleForm" :rules="rules">
                <el-form-item prop="userName">
                    <el-input v-model="ruleForm.userName" placeholder="手机号" prefix-icon="UserFilled">
                    </el-input>
                </el-form-item>
                <el-form-item prop="passWord">
                    <el-input v-model="ruleForm.passWord" placeholder="密码" type="password" prefix-icon="Lock">
                    </el-input>
                </el-form-item>
                <el-form-item v-if="!change">
                    <el-input v-model="ruleForm.validCode" placeholder="验证码" prefix-icon="Lock">
                        <template #append>
                            <span @click="countDownChange" :class="{ disabled: !canClick }"> {{ countDown.validText
                                }}</span>
                        </template>
                    </el-input>
                </el-form-item>
                <el-button type="primary" style="width: 100%;"
                    @click=sunmitForm(loginFormRef)>{{ !change ?
                        '注册' : '登录' }}</el-button>
            </el-form>
        </el-card>
    </el-row>
</template>

<style lang="less" scoped>
.el-card_header {
    padding: 0;
}

.login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    /* 确保容器高度为视口高度 */

    .card-header {
        background-color: #899f;

        img {
            width: 430px;
        }
    }

    .jump-link {
        text-align: right;
        margin-bottom: 10px;
    }

    .jump-link:hover {
        cursor: pointer;
    }

}
</style>